package com.sunday.common.sharding.sphere.jdbc.study.base.sync.obj;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: zsy
 * @Create: 2023/4/4 15:20
 */
public class SynchronizeAndObjectLock4 {

    private Object objectLock = new Object();

    /**
     * synchronized代码块修饰同一个对象时互斥
     * <p>
     * 【结论】synchronized代码块修饰同一个对象时互斥，若synchronized代码块修饰的是不同对象，那么不会互斥。
     */
    public static void main(String[] args) throws Exception {

        SynchronizeAndObjectLock4 synchronizeAndObjectLock4 = new SynchronizeAndObjectLock4();
        new Thread(() -> {
            synchronizeAndObjectLock4.test1();
        }).start();

        new Thread(() -> {
            synchronizeAndObjectLock4.test2();
        }).start();
    }

    public void test1() {
        synchronized (objectLock) {
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
            }
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
        }

    }

    public void test2() {
        synchronized (objectLock) {
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
            }
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
        }
    }

}
